package com.ostrich.demomvvm.net

import androidx.lifecycle.LiveData
import retrofit2.CallAdapter
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * @Author : yaotianxue
 * @Time : On 2023/10/18 15:21
 * @Description : LiveDataCallAdapterFactory
 */
class LiveDataCallAdapterFactory: CallAdapter.Factory() {
    override fun get(
        returnType: Type,
        annotations: Array<out Annotation>,
        retrofit: Retrofit,
    ): CallAdapter<*, *>? {
        //判断原始数据类型是否为LiveData类型
        if(getRawType(returnType) != LiveData::class.java){
            throw IllegalArgumentException("type must be LiveData")
        }
        val type = getParameterUpperBound(0, returnType as ParameterizedType)
        val rawType = getRawType(type)// BaseResponse
        //判断泛型是否为BaseResponse类型
        if(rawType != BaseResponse::class.java){
            throw IllegalArgumentException("type must be BaseResponse")
        }
        return LiveDataCallAdapter<Any>(rawType)


    }

    companion object{
        @JvmStatic
        fun create():LiveDataCallAdapterFactory{
            return LiveDataCallAdapterFactory()
        }
    }

}